package com.gmgz.controller;

import java.util.Date;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.gmgz.config.SystemConfig;
import com.gmgz.index.PicViewer;
import com.gmgz.model.Picnews;

public class PicnewsController extends Controller {
	
	public void index() {
		int page = 1;
		Page<Picnews> pageRecord = Picnews.me.paginate(page, SystemConfig.getInstance().getPageSize(), "select *", "from picnews order by idx");
			
		setAttr("pageRecord", pageRecord);
		
		renderJsp("index.jsp");
	}
	
	public void form() {
		Integer id = getParaToInt("id");
		if(id != null && id > 0) {
			// 更新
			setAttr("picnews", Picnews.me.findById(id));
		}
		
		render("form.jsp");
	}
	
	public void save() {
		UploadFile file = getFile("img");
		//System.out.println(file.getSaveDirectory());
		
		Picnews picnews = getModel(Picnews.class, "picnews");
		if(file != null) {
			picnews.set("pic", file.getFileName());
		}
		picnews.set("createTime", new Date());
		
		if(picnews.get("id") == null) {
			// 新增
			picnews.save();
		} else if(picnews.getInt("id") > 0) {
			// 更新
			picnews.update();
		}
		
		// 刷新前端缓存
		PicViewer.refreshPicnewsCache();

		index();
	}
	
	public void delete() {
		Integer id = getParaToInt("id");
		if(id != null && id > 0) {
			boolean flag = Picnews.me.deleteById(id);
			if(flag) {
				// 刷新前端缓存
				PicViewer.refreshPicnewsCache();
				
				index();
			} else {
				renderText("删除新闻失败");
			}
		} else {
			renderText("删除新闻失败");
		}
	}

}
